{% extends "base.html" %}

{% block title %}个人中心{% endblock %}

{% block content %}
<style>
/* 个人中心页面样式 */
.profile-container {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    padding: 2rem 0;
}

.profile-content {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    padding: 30px;
    margin: 20px auto;
    max-width: 1200px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
}

.profile-title {
    color: #2c3e50;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>

<div class="profile-container">
<div class="profile-content">
    <div class="row">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="profile-title"><i class="fas fa-user"></i> 个人中心</h2>
                <a href="{{ url_for('dashboard') }}" class="btn btn-outline-primary">
                    <i class="fas fa-home"></i> 返回主页
                </a>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 用户信息卡片 -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-id-card"></i> 基本信息</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-sm-4"><strong>学号:</strong></div>
                        <div class="col-sm-8">{{ user_info.id }}</div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-sm-4"><strong>姓名:</strong></div>
                        <div class="col-sm-8">{{ user_info.name }}</div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-sm-4"><strong>专业:</strong></div>
                        <div class="col-sm-8">{{ user_info.major }}</div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-sm-4"><strong>年级:</strong></div>
                        <div class="col-sm-8">{{ user_info.grade }}</div>
                    </div>
                    <form method="POST" action="{{ url_for('update_contact') }}" id="contactForm">
                        <div class="row mb-3">
                            <div class="col-sm-4"><strong>联系电话:</strong></div>
                            <div class="col-sm-8">
                                <div class="input-group">
                                    <input type="tel" class="form-control" name="phone" value="{{ user_info.phone or '' }}" placeholder="请输入联系电话">
                                    <button type="button" class="btn btn-outline-secondary" onclick="toggleEdit('phone')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-sm-4"><strong>邮箱:</strong></div>
                            <div class="col-sm-8">
                                <div class="input-group">
                                    <input type="email" class="form-control" name="email" value="{{ user_info.email or '' }}" placeholder="请输入邮箱地址">
                                    <button type="button" class="btn btn-outline-secondary" onclick="toggleEdit('email')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-sm-12 text-end">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> 保存联系方式
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 实名认证卡片 -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-shield-alt"></i> 实名认证</h5>
                </div>
                <div class="card-body">
                    <div class="text-center">
                        {% if user_info.is_verified %}
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle fa-2x mb-2"></i>
                                <h6>已完成实名认证</h6>
                                <small class="text-muted">认证时间: {{ user_info.verify_time.strftime('%Y-%m-%d %H:%M:%S') if user_info.verify_time else '未知' }}</small>
                            </div>
                            {% if user_info.profile_photo %}
                                <div class="mb-3">
                                    <img src="data:image/jpeg;base64,{{ user_info.profile_photo }}" 
                                         alt="用户头像" class="img-thumbnail" 
                                         style="width: 150px; height: 150px; object-fit: cover;">
                                </div>
                            {% endif %}
                            <button type="button" class="btn btn-outline-primary" onclick="startIdentityVerification()">
                                <i class="fas fa-sync-alt"></i> 重新认证
                            </button>
                        {% else %}
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                                <h6>尚未完成实名认证</h6>
                                <p class="mb-0">请使用人脸识别完成实名认证，以享受更多服务</p>
                            </div>
                            <button type="button" class="btn btn-primary btn-lg" onclick="startIdentityVerification()">
                                <i class="fas fa-camera"></i> 开始实名认证
                            </button>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 功能快捷入口 -->
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-th-large"></i> 快捷功能</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <a href="{{ url_for('library') }}" class="btn btn-outline-primary btn-block">
                                <i class="fas fa-book"></i><br>
                                图书馆座位预约
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="{{ url_for('schedule') }}" class="btn btn-outline-success btn-block">
                                <i class="fas fa-calendar"></i><br>
                                课程表查询
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="{{ url_for('lost_found') }}" class="btn btn-outline-warning btn-block">
                                <i class="fas fa-search"></i><br>
                                失物招领
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="{{ url_for('change_password') }}" class="btn btn-outline-danger btn-block">
                                <i class="fas fa-key"></i><br>
                                修改密码
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 消息提示模态框 -->
<div class="modal fade" id="messageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提示</h5>
                <button type="button" class="close" data-bs-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p id="messageText"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<script>
// 启动实名认证
function startIdentityVerification() {
    // 检查浏览器是否支持摄像头
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        alert('您的浏览器不支持摄像头功能');
        return;
    }
    
    // 创建实名认证模态框
    const verifyModal = document.createElement('div');
    verifyModal.className = 'modal fade';
    verifyModal.id = 'identityVerificationModal';
    verifyModal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-shield-alt"></i> 实名认证
                    </h5>
                    <button type="button" class="close" data-bs-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> 
                        请选择一张清晰的个人照片进行实名认证
                    </div>
                    
                    <!-- 选择认证方式 -->
                    <div class="mb-4">
                        <div class="btn-group w-100" role="group">
                            <button type="button" class="btn btn-outline-primary active" id="uploadModeBtn" onclick="switchMode('upload')">
                                <i class="fas fa-folder-open"></i> 上传照片
                            </button>
                            <button type="button" class="btn btn-outline-primary" id="cameraModeBtn" onclick="switchMode('camera')">
                                <i class="fas fa-camera"></i> 拍照认证
                            </button>
                        </div>
                    </div>
                    
                    <!-- 上传照片模式 -->
                    <div id="uploadContainer">
                        <div class="upload-area" style="border: 2px dashed #007bff; border-radius: 10px; padding: 40px; margin: 20px 0; background-color: #f8f9fa;">
                            <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                            <p class="mb-3">点击选择照片或拖拽照片到此处</p>
                            <input type="file" id="photoUpload" accept="image/*" style="display: none;" onchange="previewPhoto(this)">
                            <button type="button" class="btn btn-outline-primary" onclick="document.getElementById('photoUpload').click()">
                                <i class="fas fa-folder-open"></i> 选择照片
                            </button>
                        </div>
                        <div id="photoPreview" style="display: none; margin-top: 20px;">
                            <img id="previewImage" style="max-width: 400px; max-height: 300px; border-radius: 10px; border: 1px solid #ddd;">
                            <div class="mt-3">
                                <button type="button" class="btn btn-success" onclick="uploadAndVerify()">
                                    <i class="fas fa-check"></i> 确认认证
                                </button>
                                <button type="button" class="btn btn-secondary ml-2" onclick="clearPhoto()">
                                    <i class="fas fa-times"></i> 重新选择
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 拍照模式 -->
                    <div id="cameraContainer" style="display: none;">
                        <div class="camera-area" style="border: 2px solid #007bff; border-radius: 10px; padding: 20px; margin: 20px 0; background-color: #f8f9fa; text-align: center;">
                            <video id="cameraVideo" style="max-width: 400px; max-height: 300px; border-radius: 10px; display: none;"></video>
                            <canvas id="cameraCanvas" style="max-width: 400px; max-height: 300px; border-radius: 10px; display: none;"></canvas>
                            <div id="cameraPlaceholder" class="mb-3">
                                <i class="fas fa-camera fa-3x text-primary mb-3"></i>
                                <p class="mb-3">点击开启摄像头进行拍照</p>
                                <button type="button" class="btn btn-outline-primary" onclick="startCamera()">
                                    <i class="fas fa-video"></i> 开启摄像头
                                </button>
                            </div>
                            <div id="cameraControls" style="display: none; margin-top: 15px;">
                                <button type="button" class="btn btn-primary" onclick="takePhoto()">
                                    <i class="fas fa-camera"></i> 拍照
                                </button>
                                <button type="button" class="btn btn-secondary ml-2" onclick="stopCamera()">
                                    <i class="fas fa-stop"></i> 关闭摄像头
                                </button>
                            </div>
                            <div id="capturedPhotoControls" style="display: none; margin-top: 15px;">
                                <button type="button" class="btn btn-success" onclick="uploadAndVerify()">
                                    <i class="fas fa-check"></i> 确认认证
                                </button>
                                <button type="button" class="btn btn-warning ml-2" onclick="retakePhoto()">
                                    <i class="fas fa-redo"></i> 重新拍照
                                </button>
                                <button type="button" class="btn btn-secondary ml-2" onclick="stopCamera()">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                            </div>
                        </div>
                    </div>
                    <div id="verificationResult" class="mt-3"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(verifyModal);
    
    const modal = new bootstrap.Modal(verifyModal);
    modal.show();
    
    // 模态框关闭时清理资源
    verifyModal.addEventListener('hidden.bs.modal', function() {
        clearPhoto();
        stopCamera();
        document.body.removeChild(verifyModal);
    });
}

let selectedPhotoData = null;
let cameraStream = null;
let currentMode = 'upload'; // 'upload' 或 'camera'

// 切换认证模式
function switchMode(mode) {
    currentMode = mode;
    const uploadContainer = document.getElementById('uploadContainer');
    const cameraContainer = document.getElementById('cameraContainer');
    const uploadModeBtn = document.getElementById('uploadModeBtn');
    const cameraModeBtn = document.getElementById('cameraModeBtn');
    
    // 清理之前的状态
    clearPhoto();
    stopCamera();
    
    if (mode === 'upload') {
        uploadContainer.style.display = 'block';
        cameraContainer.style.display = 'none';
        uploadModeBtn.classList.add('active');
        cameraModeBtn.classList.remove('active');
    } else {
        uploadContainer.style.display = 'none';
        cameraContainer.style.display = 'block';
        uploadModeBtn.classList.remove('active');
        cameraModeBtn.classList.add('active');
    }
}

// 预览选择的照片
function previewPhoto(input) {
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            selectedPhotoData = e.target.result;
            const previewImage = document.getElementById('previewImage');
            const photoPreview = document.getElementById('photoPreview');
            
            previewImage.src = selectedPhotoData;
            photoPreview.style.display = 'block';
        };
        
        reader.readAsDataURL(file);
    }
}

// 清除选择的照片
function clearPhoto() {
    selectedPhotoData = null;
    const photoPreview = document.getElementById('photoPreview');
    const photoUpload = document.getElementById('photoUpload');
    const verificationResult = document.getElementById('verificationResult');
    
    if (photoPreview) photoPreview.style.display = 'none';
    if (photoUpload) photoUpload.value = '';
    if (verificationResult) verificationResult.innerHTML = '';
}

// 启动摄像头
async function startCamera() {
    try {
        const video = document.getElementById('cameraVideo');
        const placeholder = document.getElementById('cameraPlaceholder');
        const controls = document.getElementById('cameraControls');
        
        // 请求摄像头权限
        cameraStream = await navigator.mediaDevices.getUserMedia({ 
            video: { 
                width: { ideal: 640 }, 
                height: { ideal: 480 },
                facingMode: 'user' // 前置摄像头
            } 
        });
        
        video.srcObject = cameraStream;
        video.play();
        
        // 显示视频和控制按钮
        placeholder.style.display = 'none';
        video.style.display = 'block';
        controls.style.display = 'block';
        
    } catch (error) {
        console.error('无法启动摄像头:', error);
        alert('无法启动摄像头，请检查摄像头权限设置');
    }
}

// 拍照
function takePhoto() {
    const video = document.getElementById('cameraVideo');
    const canvas = document.getElementById('cameraCanvas');
    const controls = document.getElementById('cameraControls');
    const capturedControls = document.getElementById('capturedPhotoControls');
    
    if (!video.videoWidth || !video.videoHeight) {
        alert('摄像头未准备就绪，请稍后再试');
        return;
    }
    
    // 设置canvas尺寸
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    // 绘制当前帧到canvas
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0);
    
    // 获取base64图片数据
    selectedPhotoData = canvas.toDataURL('image/jpeg', 0.8);
    
    // 显示拍摄的照片
    video.style.display = 'none';
    canvas.style.display = 'block';
    controls.style.display = 'none';
    capturedControls.style.display = 'block';
}

// 重新拍照
function retakePhoto() {
    const video = document.getElementById('cameraVideo');
    const canvas = document.getElementById('cameraCanvas');
    const controls = document.getElementById('cameraControls');
    const capturedControls = document.getElementById('capturedPhotoControls');
    
    selectedPhotoData = null;
    
    // 重新显示视频流
    canvas.style.display = 'none';
    video.style.display = 'block';
    capturedControls.style.display = 'none';
    controls.style.display = 'block';
}

// 停止摄像头
function stopCamera() {
    if (cameraStream) {
        cameraStream.getTracks().forEach(track => track.stop());
        cameraStream = null;
    }
    
    const video = document.getElementById('cameraVideo');
    const canvas = document.getElementById('cameraCanvas');
    const placeholder = document.getElementById('cameraPlaceholder');
    const controls = document.getElementById('cameraControls');
    const capturedControls = document.getElementById('capturedPhotoControls');
    
    if (video) {
        video.style.display = 'none';
        video.srcObject = null;
    }
    if (canvas) canvas.style.display = 'none';
    if (placeholder) placeholder.style.display = 'block';
    if (controls) controls.style.display = 'none';
    if (capturedControls) capturedControls.style.display = 'none';
    
    selectedPhotoData = null;
}

// 上传照片并进行实名认证
function uploadAndVerify() {
    if (!selectedPhotoData) {
        alert('请先选择一张照片');
        return;
    }
    
    const resultDiv = document.getElementById('verificationResult');
    
    // 显示处理中状态
    resultDiv.innerHTML = '<div class="text-info"><i class="fas fa-spinner fa-spin"></i> 正在进行实名认证...</div>';
    
    // 发送图片到后端进行实名认证
    fetch('/face_recognition/identity_verify', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            image: selectedPhotoData
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            resultDiv.innerHTML = `
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> ${data.message}
                </div>
            `;
            
            // 延迟后直接刷新页面，不处理模态框关闭
            setTimeout(() => {
                location.reload();
            }, 2000);
            } else {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-times-circle"></i> ${data.message}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('认证失败:', error);
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> 认证过程中发生错误，请重试
                </div>
            `;
        });
}

// 添加拖拽上传功能
function setupDragAndDrop() {
    const uploadArea = document.querySelector('.upload-area');
    const photoUpload = document.getElementById('photoUpload');
    
    if (!uploadArea || !photoUpload) return;
    
    // 防止默认拖拽行为
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });
    
    // 高亮拖拽区域
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, unhighlight, false);
    });
    
    // 处理文件拖拽
    uploadArea.addEventListener('drop', handleDrop, false);
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    function highlight(e) {
        uploadArea.style.backgroundColor = '#e3f2fd';
        uploadArea.style.borderColor = '#2196f3';
    }
    
    function unhighlight(e) {
        uploadArea.style.backgroundColor = '#f8f9fa';
        uploadArea.style.borderColor = '#007bff';
    }
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        
        if (files.length > 0) {
            photoUpload.files = files;
            previewPhoto(photoUpload);
        }
    }
}

// 在模态框显示后设置拖拽功能
function showIdentityVerification() {
    const verifyModal = document.createElement('div');
    verifyModal.className = 'modal fade';
    verifyModal.id = 'identityVerificationModal';
    verifyModal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-shield-alt"></i> 实名认证
                    </h5>
                    <button type="button" class="close" data-bs-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> 
                        请选择一张清晰的个人照片进行实名认证
                    </div>
                    <div id="uploadContainer">
                        <div class="upload-area" style="border: 2px dashed #007bff; border-radius: 10px; padding: 40px; margin: 20px 0; background-color: #f8f9fa; transition: all 0.3s ease;">
                            <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                            <p class="mb-3">点击选择照片或拖拽照片到此处</p>
                            <input type="file" id="photoUpload" accept="image/*" style="display: none;" onchange="previewPhoto(this)">
                            <button type="button" class="btn btn-outline-primary" onclick="document.getElementById('photoUpload').click()">
                                <i class="fas fa-folder-open"></i> 选择照片
                            </button>
                        </div>
                        <div id="photoPreview" style="display: none; margin-top: 20px;">
                            <img id="previewImage" style="max-width: 400px; max-height: 300px; border-radius: 10px; border: 1px solid #ddd;">
                            <div class="mt-3">
                                <button type="button" class="btn btn-success" onclick="uploadAndVerify()">
                                    <i class="fas fa-check"></i> 确认认证
                                </button>
                                <button type="button" class="btn btn-secondary ml-2" onclick="clearPhoto()">
                                    <i class="fas fa-times"></i> 重新选择
                                </button>
                            </div>
                        </div>
                    </div>
                    <div id="verificationResult" class="mt-3"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(verifyModal);
    
    const modal = new bootstrap.Modal(verifyModal);
    modal.show();
    
    // 设置拖拽功能
    setTimeout(() => {
        setupDragAndDrop();
    }, 100);
    
    // 模态框关闭时清理资源
    verifyModal.addEventListener('hidden.bs.modal', function() {
        clearPhoto();
        stopCamera();
        document.body.removeChild(verifyModal);
    });
}

// 联系方式编辑功能
function toggleEdit(fieldName) {
    const input = document.querySelector(`input[name="${fieldName}"]`);
    if (input.readOnly) {
        input.readOnly = false;
        input.focus();
        input.style.backgroundColor = '#fff';
    } else {
        input.readOnly = true;
        input.style.backgroundColor = '#f8f9fa';
    }
}

// 页面加载时设置输入框为只读状态
document.addEventListener('DOMContentLoaded', function() {
    const phoneInput = document.querySelector('input[name="phone"]');
    const emailInput = document.querySelector('input[name="email"]');
    
    if (phoneInput) {
        phoneInput.readOnly = true;
        phoneInput.style.backgroundColor = '#f8f9fa';
    }
    
    if (emailInput) {
        emailInput.readOnly = true;
        emailInput.style.backgroundColor = '#f8f9fa';
    }
});

</script>
</div>
</div>
{% endblock %}